<?php
namespace app\common\library;

class Payment 
{
    protected static $instance = null;
    
    public static function instance()
    {
        if (is_null(self::$instance)) {
            self::$instance = new static();
        }
        return self::$instance;
    }

    /**
     * 创建支付
     * @param string $type 支付类型:wxpay=微信支付,alipay=支付宝支付
     * @param array $order 订单信息
     * @param string $notify_url 异步通知地址
     * @return array
     */
    public function create($type, $order, $notify_url)
    {
        switch ($type) {
            case 'wxpay':
                return $this->createWxPay($order, $notify_url);
            case 'alipay':
                return $this->createAliPay($order, $notify_url);
            default:
                throw new \Exception("不支持的支付方式");
        }
    }
    
    /**
     * 创建微信支付
     */
    protected function createWxPay($order, $notify_url)
    {
        $config = get_addon_config('epay');
        $wechat = \addons\epay\library\Service::submitOrder($order['order_no'], $order['amount'], 
            'wechat', $order['title'], $notify_url, ['method' => 'app']);
            
        if (!$wechat) {
            throw new \Exception("创建微信支付失败");
        }
        
        return [
            'type' => 'wxpay',
            'params' => $wechat
        ];
    }
    
    /**
     * 创建支付宝支付
     */
    protected function createAliPay($order, $notify_url)
    {
        $config = get_addon_config('epay');
        $alipay = \addons\epay\library\Service::submitOrder($order['order_no'], $order['amount'],
            'alipay', $order['title'], $notify_url, ['method' => 'app']);
            
        if (!$alipay) {
            throw new \Exception("创建支付宝支付失败");
        }
        
        return [
            'type' => 'alipay',
            'params' => $alipay
        ];
    }
    
    /**
     * 微信支付签名
     */
    protected function makeWxSign($params)
    {
        ksort($params);
        $str = '';
        foreach ($params as $k => $v) {
            if ($v !== '' && $v !== null && $k != 'sign') {
                $str .= $k . '=' . $v . '&';
            }
        }
        $str .= 'key=' . config('payment.wxpay.key');
        return strtoupper(md5($str));
    }
    
    /**
     * 支付宝签名
     */
    protected function makeAliSign($params)
    {
        ksort($params);
        $str = '';
        foreach ($params as $k => $v) {
            if ($v !== '' && $v !== null && $k != 'sign') {
                $str .= $k . '=' . $v . '&';
            }
        }
        $str = rtrim($str, '&');
        
        $private_key = config('payment.alipay.private_key');
        $res = openssl_get_privatekey($private_key);
        openssl_sign($str, $sign, $res, OPENSSL_ALGO_SHA256);
        openssl_free_key($res);
        return base64_encode($sign);
    }
}